<?php
/**
 * Created by PhpStorm.
 * User: Angry
 * Date: 2018/3/15
 * Time: 13:23
 */

namespace app\admin\controller;

use Qcloud\Cos\Client;
use think\File;
use think\Request;

class Upload
{
    private $cosClient;

    private $data;

    private $directory = '/gywl/upload/';

    public function __construct()
    {
        $this->cosClient = new Client(config('cos.default'));
    }

    public function upload(Request $request)
    {
        foreach ($request->file() as $file) {
            $filename = $this->pushCos($file, $this->directory);
            $this->data['data'][] = $filename;
        }
        $this->data['errno'] = 0;
        return json($this->data);
    }

    private function pushCos(File $file, $directory) {
        $info = $file->getInfo();
        $extArr = explode('.', $info['name']);
        $ext = array_pop($extArr);
        $filename = $directory.md5(microtime().$info['name']).'.'.$ext;
        try {
            $result = $this->cosClient->putObject([
                'Bucket' => 'pic',
                'Key' => $filename,
                'Body' => file_get_contents($info['tmp_name'])
            ]);
        } catch (\Exception $exception) {
            return false;
        }
        if ($result) return config('cos.cdn').$filename;
        return false;
    }
}